package com.bnz.security.service;

import com.bnz.security.entity.Users;
import com.bnz.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 自定义验证规则
 */
@Service
public class MyDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        if (!"admin".equalsIgnoreCase(username)){
//            throw new UsernameNotFoundException("用户名不存在");
//        }
//        String password = "$2a$10$tgadtlZUE.iQFkqWISAggu4.sNd6MD0L5blTxnok.sw2OZX0ohmkG";

        //1. 从数据库中查询用户
        Users user = new Users();
        user.setUsername(username);
        Users users = userMapper.selectOne(user);
        //2. 返回认证的用户
        //2.1 其中的角色必须以ROLE_开头,否则找不到
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("user1,admin,ROLE_user,ROLE_admin");

        return new User(username,users.getPassword(),authorities);
    }
}
